<template>
	<view class="page">
		<view class="page__list">
			<view class="">
				<text>异常点位：</text>
				<text>{{data.cnl_code}}</text>
			</view>
			<view class="">
				<text>异常时间：</text>
				<text>{{data.chat_time}}</text>
			</view>
			<view class="">
				<text>异常描述：</text>
				<view class="" v-html="data.text"></view>
			</view>
		</view>
		<view class="page__card">
			<view class="page__card--head">
				<text style="color: red;">*</text>
				<text>异常备注</text>
			</view>
			<view class="page__card--textarea">
				<input v-model="bug" placeholder="请输入备注"></input>
			</view>
		</view>
		<view class="page__card">
			<view class="page__card--head">处理建议</view>
			<view class="page__card--textarea">
				<textarea v-model="sug" placeholder="请输入建议"></textarea>
			</view>
		</view>
		<view class="page__date">
			<view class="">
				<u-icon name="arrow-left" color="#666" size="20" @click="prev"></u-icon>
			</view>
			<view class="" @click="dateVisible = true">{{date}}</view>
			<view class="">
				<u-icon name="arrow-right" color="#666" size="20" @click="next"></u-icon>
			</view>
		</view>
		<view class="page__chart">
			<chart :options="option" />
		</view>

		<u-datetime-picker :show="dateVisible" v-model="defaultDate" mode="date" closeOnClickOverlay
			@cancel="dateVisible = false" @close="dateVisible = false" @confirm="dateConfirm"></u-datetime-picker>
	</view>
</template>

<script>
	import _custom from '@/common/_custom.js'
	import _mixins from '@/common/_mixins';
	import _data from '@/common/_data.js'
	import moment from 'moment';
	import Chart from '@/components/custom/chart/echart.vue';

	export default {
		components: {
			Chart
		},
		data() {
			return {
				obsusername: _data.localData('name'),
				data: {},
				option: {
					animation: false,
					legend: {
						left: '2%',
						bottom: '0',
						icon: "circle",
						itemWidth: 10,
						itemHeight: 10,
						textStyle: {
							color: '#333',
							fontSize: 14,
						},
						data: [{
							name: '',
						}],
					},
					dataZoom: { // 放大和缩放
						type: 'inside'
					},
					tooltip: {
						trigger: 'axis',
						confine: true,
						format: 'markPointTooltipFormat'
					},
					grid: {
						top: '15%',
						left: '13%',
						bottom: '16%',
						right: '5%'
					},
					xAxis: [{
						type: 'time',
						min: '',
						max: '',
						minInterval: 24,
						boundaryGap: false,
						axisTick: {
							show: false,
						},
						axisLabel: {
							format: 'xLabelFormat'
						},
						splitLine: {
							show: false,
						},
						axisLine: {
							show: true,
							lineStyle: {
								color: '#666'
							},
						},
					}],
					yAxis: {
						type: 'value',
						name: '',
						nameTextStyle: {
							color: '#666',
							padding: [0, 0, 0, 0],
						},
						axisLine: {
							show: true,
							lineStyle: {
								color: '#666'
							},
						},
					},
					series: [{
						name: '',
						data: [],
						type: 'line',
						itemStyle: {
							normal: {
								width: 1,
								color: '#fbb034',
							},
						},
						symbol: 'none',
						label: {
							show: false,
						},
						areaStyle: {
							color: {
								type: 'linear',
								x: 0,
								y: 0,
								x2: 0,
								y2: 1,
								colorStops: [{
										offset: 0,
										color: '#fbb034',
									},
									{
										offset: 0.8,
										color: 'rgba(255, 222, 181, 0.5)',
									}
								],
								global: false
							}
						},
						markPoint: {
							data: [],
							tooltip: {
								trigger: 'item',
								format: 'markPointTooltipFormat'
							},
						},
						markLine: {
							show: true,
							symbol: 'none',
							label: {
								show: true, //显示文本
							},
							lineStyle: {
								type: 'solid',
								width: 1,
								color: "rgba(255,0,0,.5)",
							},
							data: []
						}
					}]
				},
				bug: '',
				sug: '',
				date: '',
				defaultDate: '',
				dateVisible: false,
				showDevice: false,
			}
		},
		onLoad(options) {
			if (options.data) {
				this.data = JSON.parse(options.data);
				this.date = moment(this.data.chat_time).format('YYYY-MM-DD');
				this.defaultDate = moment(this.data.chat_time).format('YYYY-MM-DD');
				this.option.series[0].name = this.data.cnl_code;
				if (this.data.back_id == 0) {
					this.getChatAlarmBackSuggest()
				} else {
					this.getChatAlarmBackById();
				}
				this.getChartData();
			}
		},
		onNavigationBarButtonTap(e) {
			if (!this.bug) {
				uni.showToast({
					title: '请输入异常备注',
					icon: 'none'
				})
				return
			}
			this.addAndUpdateChatAlarmBack()
		},
		methods: {
			/**
			 * 获取tablesuffix
			 * @param {Object} date
			 */
			getTableSuffix(date) {
				let year = (moment(date).year() + '').substr(2)
				let month = moment(date).month() + 1
				month = month < 10 ? '0' + month : month
				let tablesuffix = this.data.obscode + "_" + year + month
				return tablesuffix
			},
			/**
			 * 获取图表的数据并设置相关参数
			 */
			getChartData() {
				Promise.all([this.getCnlDataList(), this.getChatAlarmInfoList()]).then(res => {
					let cnlData = res[0];
					if (!cnlData.length) {
						this.option.series[0].data = [];
						return
					}
					let alarmInfo = res[1];
					let max = 0;
					let data = cnlData.map(item => {
						if(max < item.Val*1) max = item.Val*1;
						return {
							value: [moment(item.DateTime).format('x') * 1, (item.Val * 1).toFixed(2)],
							datetime: item.DateTime
						}
					})
					alarmInfo.forEach(v => {
						data.push({
							value: [moment(v.ChatTime).format('x') * 1, (v.Val * 1).toFixed(2)],
							name: v.Reason,
							datetime: v.ChatTime
						})
					})
					for(let i=0;i<data.length;i++) {
						for(let j=0;j<data.length;j++) {
							if(moment(data[i].datetime).isAfter(data[j].datetime, 'second')) {
								let temp = data[i];
								data[i] = data[j];
								data[j] = temp
							}
						}
					}

					this.option.xAxis[0].min = moment(this.date).format('YYYY-MM-DD') + ' 00:00';
					this.option.xAxis[0].max = moment(this.date).format('YYYY-MM-DD') + ' 23:59';
					this.option.series[0].data = data;
					this.option.yAxis.name = cnlData[0].Unit;

					let markPoint = []
					alarmInfo.forEach(item => {
						let xVal = moment(item.ChatTime).format('x') * 1;
						let yVal = item.Val * 1;
						markPoint.push({
							name: item.Reason,
							coord: [xVal, yVal],
							itemStyle: {
								color: "red"
							},
							symbol: 'image://static/theme/default/home/gaojing.png',
							symbolSize: 20,
							z: 3
						})
					})
					if(this.date == moment(this.data.chat_time).format('YYYY-MM-DD')) {
						let time = moment(this.data.chat_time).format('YYYY-MM-DD HH:mm') + ':00'
						this.option.series[0].markLine.data = [[{
							coord: [moment(time).format('x') * 1,0],
					  },{
						  coord: [moment(time).format('x') * 1,max],
					  }]]
					}
					this.option.series[0].markPoint.data = markPoint
				})
			},
			/**
			 * 获取点位小时平均数据
			 */
			getCnlDataList() {
				let that = this;
				return new Promise((resolve, reject) => {
					_custom.getDataJava({
						apiname: 'getCnlDataList',
						apiparam: {
							obscode: this.data.obscode,
							tablesuffix: this.getTableSuffix(this.date),
							cnlcode: this.data.cnl_code,
							startdate: moment(this.date).format('YYYY-MM-DD'),
							enddate: moment(this.date).format('YYYY-MM-DD')
						},
						success(res) {
							resolve(res)
						}
					})
				})
			},
			/**
			 * 点标记数据
			 */
			getChatAlarmInfoList() {
				let that = this;
				return new Promise((resolve, reject) => {
					_custom.getDataJava({
						apiname: 'getChatAlarmInfoList',
						apiparam: {
							obscode: this.data.obscode,
							cnlcode: this.data.cnl_code,
							startdate: moment(this.date).format('YYYY-MM-DD'),
							enddate: moment(this.date).format('YYYY-MM-DD')
						},
						success(res) {
							resolve(res)
						}
					})
				})
			},
			/**
			 * 添加或更新数据
			 */
			addAndUpdateChatAlarmBack() {
				let that = this;
				_custom.getDataJava({
					apiname: 'addAndUpdateChatAlarmBack',
					apiparam: {
						obscode: this.data.obscode,
						backid: this.data.back_id,
						obsusername: this.obsusername,
						chattime: this.data.chat_time,
						cnlcode: this.data.cnl_code,
						val: this.data.val,
						reason: this.bug,
						suggest: this.format1(this.sug),
					},
					success(res) {
						if (res.length && res[0].backid && that.data.back_id == 0) {
							that.updateBackId(res[0].backid)
						}
						uni.showToast({
							title: '保存成功',
							icon: 'none'
						})
						setTimeout(() => {
							uni.navigateBack()
						}, 500)
					}
				})
			},
			/**
			 * 获取历史建议
			 */
			getChatAlarmBackSuggest() {
				let that = this;
				_custom.getDataJava({
					apiname: 'getChatAlarmBackSuggest',
					apiparam: {
						obscode: this.data.obscode,
						cnlcode: this.data.cnl_code,
					},
					success(res) {
						if (res.length && res[0].Suggest) that.sug = that.format2(res[0].Suggest);
					}
				})
			},
			/**
			 * 获取相关数据
			 */
			getChatAlarmBackById() {
				let that = this;
				_custom.getDataJava({
					apiname: 'getChatAlarmBackById',
					apiparam: {
						backid: this.data.back_id,
					},
					success(res) {
						if (res.length) {
							that.bug = res[0].Reason;
							that.sug = res[0].Suggest ? that.format2(res[0].Suggest) : res[0].Suggest;
						}
					}
				})
			},
			/**
			 * 更新通知的已读状态
			 * @param {Object} v
			 */
			updateBackId(v) {
				_mixins.methods.$httpSend({
					path: '/im/alarm/updateBackId',
					data: {
						_id: this.data.id,
						back_id: v
					},
				});
			},
			format1(strValue) {
				return strValue.replace(/\r\n/g, '|').replace(/\n/g, '|');
			},
			format2(strValue) {
				return strValue.replace(/\|/g, '\r\n').replace(/\|/g, '\n');
			},
			prev() {
				this.date = moment(this.date).subtract(1, 'day').format('YYYY-MM-DD');
				this.getChartData();
			},
			next() {
				this.date = moment(this.date).subtract(-1, 'day').format('YYYY-MM-DD');
				this.getChartData();
			},
			/**
			 * 确认日期
			 */
			dateConfirm(e) {
				this.date = moment(e.value).format('YYYY-MM-DD')
				this.getChartData();
				this.dateVisible = false;
			},
		}
	}
</script>

<style scoped lang="scss">
	.page {

		&__date {
			width: 100%;
			height: 100rpx;
			background-color: #fff;
			line-height: 100rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 0 40rpx;
			box-sizing: border-box;
		}

		&__chart {
			height: 400rpx;
			background-color: #fff;
			padding-top: 20rpx;
		}

		&__list {
			background-color: #fff;
			padding: 20rpx;
		}

		&__card {
			margin: 10rpx 20rpx;
			background-color: #fff;
			border-radius: 10rpx;

			&--head {
				height: 60rpx;
				line-height: 60rpx;
				text-align: center;
			}

			&--history-sug {
				padding: 0 20rpx;
				box-sizing: border-box;
				display: flex;
				justify-content: space-between;
			}

			&--textarea {
				padding: 20rpx;
				box-sizing: border-box;

				textarea {
					height: 200rpx;
					font-size: 30rpx;
				}
			}
		}

		&__btn {
			margin: 20rpx;
		}
	}
</style>
